const Router = require('@koa/router')
const model = require("../app/models")
const resData = require('../utils/response')

const router = new Router()

const menu = model.menu
const account = model.account
const userinfo = model.userinfo

router.post('/login', async (ctx) => {
    let { name, password } = ctx.request.body
    try {
        var result = await account.findOne({ where: { name }})
        if (result && password == result.password) {
            var token = result.uuid
            ctx.body = resData(200, '登录成功', token)
        } else {
            ctx.body = resData(-10000, '登录失败, 账号或密码错误')
        }
    } catch (error) {
        ctx.body = resData(-12000, '登录失败,' + error)
    }
})
router.get('/logout', async (ctx) => {
    ctx.body = resData(200, '退出成功')
})
router.get('/regist', async (ctx) => {
    let { name, password } = ctx.request.body
    try {
        await account.create({ name, password })
        ctx.body = resData(200, '注册成功')
    } catch (error) {
        ctx.body = error
        ctx.body = resData(-13000, '注册失败,' + error)
    }
})
router.get('/info', async (ctx) => {
    var accid = ctx.request.header.authorization
    try {
        var user = await userinfo.findOne({ where: { accid }})
        var id = JSON.parse(user.menus)
        var menus = await menu.findAll({ where: { id } })
        ctx.body = resData(200, '', { user, menus })
    } catch (error) {
        console.log(error)
        ctx.body = resData(-13000, error)
    }
})
router.get('/list', async (ctx) => {
    var accid = ctx.request.header.authorization
    if (!accid) {
        ctx.body = resData(-100, '需要登陆后访问')
        return false
    }
    try {
        userinfo.belongsTo(account, { foreignKey: 'accid', targetKey: 'uuid' });
        var result = await userinfo.findAll({
            // attributes: ['nickname'],
            include: {
                model: account,
                attributes: ['name'],
            }
        })
        ctx.body = resData(200, '', result)
    } catch (error) {
        ctx.body = resData(-13000, error)
    }
})
module.exports = router;
